package com.bill99.golden.inf.sso.util;

import com.bill99.golden.inf.sso.mdp.model.SsoTokenInfo;
import com.bill99.golden.inf.sso.service.ITokenLog;

public class TokenLogUtil {
	private static ITokenLog tokenLog;

	public static void setTokenLog(ITokenLog tokenLog) {
		TokenLogUtil.tokenLog = tokenLog;
	}

	public static void onCreateToken(String token, final SsoTokenInfo tokenInfo) {
		if (tokenLog == null)
			return;
		try {
			TokenLogTask t = new TokenLogTask(tokenLog, "onCreateToken", token,
					tokenInfo, null);
			t.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void onValidateToken(String token,
			final SsoTokenInfo tokenInfo, String validateResult) {
		if (tokenLog == null)
			return;
		try {
			TokenLogTask t = new TokenLogTask(tokenLog, "onValidateToken",
					token, tokenInfo, validateResult);
			t.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void onRefreshToken(String token, final SsoTokenInfo tokenInfo) {
		if (tokenLog == null)
			return;
		try {
			TokenLogTask t = new TokenLogTask(tokenLog, "onRefreshToken",
					token, tokenInfo, null);
			t.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void onDestroyToken(String token, final SsoTokenInfo tokenInfo) {
		if (tokenLog == null)
			return;
		try {
			TokenLogTask t = new TokenLogTask(tokenLog, "onDestroyToken",
					token, tokenInfo, null);
			t.start();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class TokenLogTask extends Thread {
	ITokenLog tokenLog;
	String method;
	String token;
	final SsoTokenInfo tokenInfo;
	String validateResult;

	public TokenLogTask(ITokenLog tokenLog, String method, String token,
			final SsoTokenInfo tokenInfo, String validateResult) {
		super();
		this.tokenLog = tokenLog;
		this.method = method;
		this.token = token;
		this.tokenInfo = tokenInfo;
		this.validateResult = validateResult;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		if (this.tokenLog != null) {
			try {
				if ("onCreateToken".equals(this.method)) {
					this.tokenLog.onCreateToken(this.token, this.tokenInfo);
				} else if ("onValidateToken".equals(this.method)) {
					this.tokenLog.onValidateToken(this.token, this.tokenInfo,
							this.validateResult);
				} else if ("onRefreshToken".equals(this.method)) {
					this.tokenLog.onRefreshToken(this.token, this.tokenInfo);
				} else if ("onDestroyToken".equals(this.method)) {
					this.tokenLog.onDestroyToken(this.token, this.tokenInfo);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
